import axios from "axios";
import {useTokenStore} from "@/stores/token.js";
import {ElMessage} from 'element-plus'
import router from "@/router/index.js";
import {useUserStore} from "@/stores/user.js";

//创建axios的对象
const service = axios.create({
    baseURL: import.meta.env.VITE_SERVER_ADDR
});

//Axios的请求拦截器
service.interceptors.request.use(req => {
    const tokenStore = useTokenStore();
    if (tokenStore.tokenStr) {
        req.headers.token = tokenStore.tokenStr;
    }
    return req;
}, error => {

});
// service.interceptors.request.use(function (config) {
//     const tokenStore = useTokenStore();
//     if (!config.url.startsWith("/admin/login")) {
//         // config.headers.token = sessionStorage.getItem('token');
//         config.headers.token = tokenStore.tokenStr;
//     }
//     return config;
// }, function (error) {
//     return Promise.reject(error);
// });


//响应拦截器
service.interceptors.response.use(resp => {
    //刷新token
    const token = resp.headers.token;
    if (token) {
        const tokenStore = useTokenStore();
        tokenStore.updateToken(token);
    }
    return resp.data;
}, error => {
    if (error.status == 403) {
        ElMessage.error({
            message: '令牌错误,请重新登录',
            duration: 1200,
            onClose: () => {
                const tokenStore = useTokenStore();
                const userStore = useUserStore()
                tokenStore.$reset();
                userStore.$reset();
                let currentPath = router.currentRoute.value.path
                if (currentPath.startsWith("/admin")) {
                    //跳转到登录页
                    router.push("/admin/login");
                } else {
                    router.push('/user/login');
                }
            }
        })
    }
});

export default service;